package com.spzx.product.help;

import com.spzx.product.api.domain.vo.CategoryVo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CategoryHelper {
    public static List<CategoryVo> buildTree(List<CategoryVo> categoryVoList) {
        Map<Long, CategoryVo> categoryMap = new HashMap<>();
        List<CategoryVo> trees = new ArrayList<>();

        // 将所有分类放入哈希表中，以便快速查找
        for (CategoryVo categoryVo : categoryVoList) {
            categoryMap.put(categoryVo.getId(), categoryVo);
        }

        // 构建树
        for (CategoryVo categoryVo : categoryVoList) {
            if (categoryVo.getParentId().longValue() == 0) {
                trees.add(buildBranch(categoryVo, categoryMap));
            }
        }

        return trees;
    }

    private static CategoryVo buildBranch(CategoryVo categoryVo, Map<Long, CategoryVo> categoryMap) {
        List<CategoryVo> children = new ArrayList<>();
        for (CategoryVo it : categoryMap.values()) {
            if (categoryVo.getId().longValue() == it.getParentId().longValue()) {
                children.add(buildBranch(it, categoryMap));
            }
        }
        categoryVo.setChildren(children);
        return categoryVo;
    }
}
